
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.logger import logger

from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.routing import APIRoute

from apps.api.endpoints import router as endpoints_router
from apps.pages.view import index_router
import datetime

def custom_generate_unique_id(route: APIRoute) -> str:
    return f"{route.tags[0]}-{route.name}"


@asynccontextmanager
async def lifespan(app: FastAPI):
    logger.info("app开始启动")

    # todo! 注册数据库

    logger.info("app启动成功")
    yield
    # todo! 释放资源
    logger.info("app关闭成功")


app = FastAPI(
    title="后门攻击检测验证API",
    generate_unique_id_function=custom_generate_unique_id,
    lifespan=lifespan,
)


@app.on_event("startup")
async def startup_event():
    logger.info('Server started :', datetime.datetime.now())


@app.on_event("shutdown")
async def shutdown_event():
    logger.info('server Shutdown :', datetime.datetime.now())


templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="static"), name="static")

# 增加跨域配置
# app.add_middleware(
#     CORSMiddleware,
#     allow_origins=["*"],
#     allow_credentials=True,
#     allow_methods=["*"],
#     allow_headers=["*"],
# )

# 注册路由
app.include_router(index_router, tags=["视图模块"])
app.include_router(endpoints_router, prefix="/api/v1")
